/**
 * 更新检测
**/
import moment from '@/util/moment'
import zutil from '@/util/util'
module.exports = {
	zcheckUpdate (type){
		let zuiPlatform = uni.getSystemInfoSync().platform;
		let zuiPlatformType = zuiPlatform == 'android' ? 1 : 2;
		uni.setStorageSync('zuiPlatformType', zuiPlatformType);
		
		// 判断是否检测更新
		let lastCheckUpdate = uni.getStorageSync('lastCheckUpdate') || '2019-01-01',
			curCheckUpdate = moment().format('YYYY-MM-DD'),
			ignoreVersion = uni.getStorageSync('ignoreVersion') || '',
			curVersion = plus.runtime.version;
		
		let interDay = moment(curCheckUpdate).diff(moment(lastCheckUpdate), 'd');
		if(interDay >= 7){
			// 需要检测
			if(type && type == '1'){
				uni.showLoading({title: '加载中', mask: true});
			}
			zutil.zuiCommon.ajaxGet('/api/appclient/v1/appversion/info', (res)=>{
				if(res.code == '0'){
					/* let cjson = {
						"appid":"__UNI__6E8631C",
						"version":"1.0.1",
						"note":"Android新版本描述信息，多行使用\n分割555",
						"url":"http://www.dcloud.io/helloh5p/HelloH5.apk"
					} */
					let cjson = res.data;
					
					// 判断版本号是否忽略
					if(ignoreVersion !== cjson.version){
						if(type && type == '1'){
							uni.hideLoading();
						}
						// 判断版本号是否大于当前版本号
						if(this.compareVersion(curVersion, cjson.version)){
							uni.showModal({ //提醒用户更新
								title: '更新提示',
								confirmText: "立即下载",
								cancelText: "忽略",
								content: cjson.note ? cjson.note : '系统检测到有新版本，是否更新？',
								success: (res) => {
									if (res.confirm) {
										plus.runtime.openURL(cjson.url);
									}else{
										uni.setStorageSync('ignoreVersion', cjson.version);
									}
								}
							})
						}else{
							if(type && type == '1'){
								uni.showToast({
									title: `已经是最新版本了(${curVersion})`,
									duration: 2000,
									mask: false,
									icon: "none",
								})
							}
						}
					}
				}
				try{
					if(type && type == '1'){
						uni.hideLoading();
					}
				}catch(e){
					//TODO handle the exception
				}
			})
		}
	},
	compareVersion(ov, nv) {
		if (!ov || !nv || ov == "" || nv == "") {
			return false;
		}
		var b = false,
			ova = ov.split(".", 4),
			nva = nv.split(".", 4);
		for (var i = 0; i < ova.length && i < nva.length; i++) {
			var so = ova[i],
				no = parseInt(so),
				sn = nva[i],
				nn = parseInt(sn);
			if (nn > no || sn.length > so.length) {
				return true;
			} else if (nn < no) {
				return false;
			}
		}
		if (nva.length > ova.length && 0 == nv.indexOf(ov)) {
			return true;
		}
	}
}